<?php
namespace Components\Account\User\Wallet;

use Components\Account\User\Adapter;

class Service {
  public function getFieldKey($field) {
  	switch($field) {
  		case 1:
  		case '1':
  			return ['code'=>0,'key'=>'Goods'];
  		case 2:
  		case '2':
  			return ['code'=>0,'key'=>'DeclarationCoin'];
  		case 3:
  		case '3':
  			return ['code'=>0,'key'=>'TourismIntegration'];
  		case 4:
  		case '4':
  			return ['code'=>0,'key'=>'Coupon'];
  		case 5:
  		case '5':
  			return ['code'=>0,'key'=>'ActivationCode'];
  		default:
  			return ['code'=>-1,'message'=>'此钱包日志字段不存在'];
  	}
  }

  public function findFirst($parameters = []) {
    $model = Model::findFirst($parameters);
    if(!$model) {
      return ['code' => -1, 'message' => '钱包不存在或已删除'];
    }

    return ['code' => 0, 'model'=>$model];
  }

  public function sell($fields, $from_user_id, $amount, $remark = '') {
		$currentField = $this -> getFieldKey($fields);
    if($currentField['code'] != 0) { return $currentField; }

		$serviceClass = __NAMESPACE__ . '\\' . $currentField['key'] . 'Service';
		$service = new $serviceClass();

		return $service -> sell($from_user_id, $amount, $remark);
  }
  
  /**
    * @description 重复消费,
    * @param $id     integer 来源用户ID
    * @param $amount float   数量
    * @param $remark string  备注
    * @return array
    **/
  public function repeated($id, $amount, $remark = '') {
    $currentTime = time();

    $res = $this -> updateAmount([
      'to_user_id' => $id,
      'from_user_id' => $id,
      'field' => 1,
      'amount' => -$amount,
      'log_data' => [
        'user_id' => $id,
        'from_user_id' => $id,
        'type' => 52,
        'remark' => $remark . '-重复消费',
        'create_time' => $currentTime,
        'service_charge' => 0,
        'is_draw' => 1,
        'draw_time' => $currentTime
      ]
    ]);
    if($res['code'] != 0) {
      return $res;
    }
    
    // 重消奖
    $resCurrentUser = Adapter::getServiceInstance() -> findFirst([
      'conditions' => 'user_id = ' . $id,
      'columns' => 'promotion_user_id'
    ]);
    if($resCurrentUser['code'] == 0) {
      if($resCurrentUser['model'] -> promotion_user_id > 0) {
        $resCurrentParentUser = Adapter::getServiceInstance() -> findFirst([
          'conditions' => 'user_id = ' . $resCurrentUser['model'] -> promotion_user_id,
          'columns' => 'promotion_user_id'
        ]);

        $resLogModelInfo = (new Log\Service()) -> getModelClassNameByField(1);

        $i = 1;
        while(true) {
          if($i > 30) {
            break;
          }

          if($resCurrentParentUser['code'] != 0) {
            break;
          }

          if($resCurrentParentUser['model'] -> promotion_user_id <= 0) {
            break;
          }

          (new $resLogModelInfo['class_name']([
            'user_id' => $resCurrentParentUser['model'] -> promotion_user_id,
            'from_user_id' => $id,
            'type' => 87,
            'active' => 1,
            'create_time' => $currentTime,
            'amount' => 30,
            'amount_new' => 0,
            'amount_old' => 0,
            'remark' => $remark . '-重复消费',
            'service_charge' => 3,
            'is_draw' => 0,
            'draw_time' => 0
          ])) -> create();

          $resCurrentParentUser = Adapter::getServiceInstance() -> findFirst([
            'conditions' => 'user_id = ' . $resCurrentParentUser['model'] -> promotion_user_id,
            'columns' => 'promotion_user_id'
          ]);

          $i += 1;
        }
      }
    }
    
    return $this -> deposit(4, $id, $id, 20000, $remark . '-重复消费');
  }

  public function transfer($fields, $from_user_id, $to_user_id, $amount, $service_charge = 0, $remark = '') {
    $resLogModelInfo = (new Log\Service()) -> getModelClassNameByField($fields);
    if($resLogModelInfo['code'] != 0) { return $resLogModelInfo; }

    if($from_user_id == $to_user_id) { return ['code' => -1, 'message' => '不能转账给自己']; }

    if($amount <= 0) { return ['code' => -1, 'message' => '数量不能少于0']; }

    $resFromWallet = $this -> findFirst('user_id = ' . $from_user_id);
    if($resFromWallet['code'] != 0) { return $resFromWallet; }
    if($amount > $resFromWallet['model'] -> {$resLogModelInfo['field']}) {
      return ['code'=>-1,'message'=>$resLogModelInfo['name'].'数量不足'];
    }

    $resToWallet = $this -> findFirst('user_id = ' . $to_user_id);
    if($resToWallet['code'] != 0) { return $resToWallet; }

    $transaction = (new \Phalcon\Mvc\Model\Transaction\Manager()) -> get();
    $walletLogArray = [
      'create_time' => time(),
      'amount' => $amount,
      'service_charge' => $service_charge,
      'is_draw' => 1,
      'draw_time' => time()
    ];
    $walletLogArray['user_id'] = $from_user_id;
    $walletLogArray['from_user_id'] = $to_user_id;
    $walletLogArray['type'] = 32;
    $walletLogArray['active'] = 0;
    $walletLogArray['amount_old'] = $resFromWallet['model'] -> {$resLogModelInfo['field']};
    $walletLogArray['remark'] = $remark . '-' . $resLogModelInfo['name'] . '转出';
    $fromWalletLog = new $resLogModelInfo['class_name']($walletLogArray);

    $walletLogArray['user_id'] = $to_user_id;
    $walletLogArray['from_user_id'] = $from_user_id;
    $walletLogArray['type'] = 31;
    $walletLogArray['active'] = 1;
    $walletLogArray['amount_old'] = $resToWallet['model'] -> {$resLogModelInfo['field']};
    $walletLogArray['remark'] = $remark . '-' . $resLogModelInfo['name'] . '转入';
    $toWalletLog = new $resLogModelInfo['class_name']($walletLogArray);

    try {
      $resFromWallet['model'] -> setTransaction($transaction);
      $resFromWallet['model'] -> {$resLogModelInfo['field']} -= $amount;
      if(!$resFromWallet['model'] -> save()) {
        $messages = $resFromWallet['model'] -> getMessages();
        $transaction -> rollback($messages[0] -> getMessage());
      }

      $fromWalletLog -> setTransaction($transaction);
      $fromWalletLog -> amount_new = $resFromWallet['model'] -> {$resLogModelInfo['field']};
      if(!$fromWalletLog -> create()) {
        $messages = $fromWalletLog -> getMessages();
        $transaction -> rollback($messages[0] -> getMessage());
      }

      $resToWallet['model'] -> setTransaction($transaction);
      $resToWallet['model'] -> {$resLogModelInfo['field']} += $amount;
      if(!$resToWallet['model'] -> save()) {
        $messages = $resToWallet['model'] -> getMessages();
        $transaction -> rollback($messages[0] -> getMessage());
      }

      $toWalletLog -> setTransaction($transaction);
      $toWalletLog -> amount_new = $resToWallet['model'] -> {$resLogModelInfo['field']};
      if(!$toWalletLog -> create()) {
        $messages = $toWalletLog -> getMessages();
        $transaction -> rollback($messages[0] -> getMessage());
      }

      $transaction -> commit();
    } catch(\Exception $e) {
      return ['code' => -1, 'message' => $e -> getMessage()];
    }

    return ['code' => 0, 'message' => '转账成功'];
  }

  public function updateAmount($parameters) {
    if($parameters['amount'] > 0) {
      $active = 1;
    } else if($parameters['amount'] < 0) {
      $active = 0;
    } else {
      return ['code' => -1, 'message' => '数量有误'];
    }

    $resLogModelInfo = (new Log\Service()) -> getModelClassNameByField($parameters['field']);
    if($resLogModelInfo['code'] != 0) {
      return $resLogModelInfo;
    }

    $resWallet = $this -> findFirst('user_id = ' . $parameters['to_user_id']);
    if($resWallet['code'] != 0) {
      return $resWallet;
    }

    $parameters['amount'] = abs($parameters['amount']);
    
    $LogModel = new $resLogModelInfo['class_name']($parameters['log_data']);
    $LogModel -> active = $active;
    $LogModel -> amount = $parameters['amount'];
    $LogModel -> amount_old = $resWallet['model'] -> {$resLogModelInfo['field']};

    switch($active) {
      case 0:
      case '0':
        if($parameters['amount'] > $resWallet['model'] -> {$resLogModelInfo['field']}) {
          return ['code'=>-1,'message'=>$resLogModelInfo['name'].'数量不足'];
        }
        $resWallet['model'] -> {$resLogModelInfo['field']} -= $parameters['amount'];
        break;
      case 1:
      case '1':
        $resWallet['model'] -> {$resLogModelInfo['field']} += $parameters['amount'];
        break;
      default:
        return ['code' => -1, 'message' => '操作设置有误'];
    }

    if(!$resWallet['model'] -> save()) {
      return ['code' => -1, 'message' => '操作失败'];
    }

    $LogModel -> amount_new = $resWallet['model'] -> {$resLogModelInfo['field']};
    if(!$LogModel -> create()) {
      return ['code' => -1, 'message' => '操作失败'];
    }

    return ['code' => 0, 'message' => '操作成功'];
  }

  /**
   * @description 充值,
   * @param $fields       integer 字段类型
   * @param $from_user_id integer 来源用户ID
   * @param $to_user_id   integer 去向用户ID
   * @param $amount       float   数量
   * @param $type         integer 类型
   * @param $remark       string  备注
   * @return array
   **/
  public function deposit($fields, $from_user_id, $to_user_id, $amount, $remark = '') {
    $currentTime = time();
    $fieldName = '未定义';
    switch($fields) {
      case 1:
      case '1':
        $field = 'goods';
        $fieldName = '货';
        $LogModel = new Log\GoodsLogModel([
          'service_charge' => 0,
          'is_draw' => 1,
          'draw_time' => $currentTime
        ]);
        break;
      case 2:
      case '2':
        $field = 'declaration_coin';
        $fieldName = '报单币';
        $LogModel = new Log\DeclarationCoinLogModel();
        break;
      case 3:
      case '3':
        $field = 'tourism_integration';
        $fieldName = '旅游积分';
        $LogModel = new Log\TourismIntegrationLogModel();
        break;
      case 4:
      case '4':
        $field = 'coupon';
        $fieldName = '购物券';
        $LogModel = new Log\CouponLogModel();
        break;
      case 5:
      case '5':
        $field = 'activation_code';
        $fieldName = '激活码';
        $LogModel = new Log\ActivationCodeLogModel();
        break;
      default:
        return ['code' => -1, 'message' => '充值类型有误'];
    }

    $returnArray = [];
    if($amount > 0) {
      $active = 1;
      $returnArray['message'] = '充值成功';
      $res = $this -> findFirst('user_id = ' . $to_user_id);
    } else if($amount < 0) {
      $active = 0;
      $returnArray['message'] = '扣除成功';
      $res = $this -> findFirst('user_id = ' . $to_user_id);
    } else {
      return ['code' => -1, 'message' => '数量有误'];
    }
    if($res['code'] != 0) {
      return $res;
    }

    $amount = abs($amount);
    $LogModel -> user_id = $to_user_id;
    $LogModel -> from_user_id = $from_user_id;
    $LogModel -> type = 11;
    $LogModel -> active = $active;
    $LogModel -> amount = $amount;
    $LogModel -> amount_old = $res['model'] -> $field;
    $LogModel -> create_time = $currentTime;
    $LogModel -> remark = $remark . '-充值操作-' . $returnArray['message'];

    switch($active) {
      case 0:
      case '0':
        if($amount > $res['model'] -> $field) {
          $resArray = ['code' => -1];
          return ['code'=>-1,'message'=>$fieldName.'数量不足'];
        }
        $res['model'] -> $field -= $amount;
        break;
      case 1:
      case '1':
        $res['model'] -> $field += $amount;
        break;
      default:
        return ['code' => -1, 'message' => '操作设置有误'];
    }

    if(!$res['model'] -> save()) {
      return ['code' => -1, 'message' => '操作失败'];
    }

    $LogModel -> amount_new = $res['model'] -> $field;
    if(!$LogModel -> create()) {
      return ['code' => -1, 'message' => '操作成功'];
    }

    $returnArray['code'] = 0;
    return $returnArray;
  }
}
